package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.book.bean.Book;
import com.book.biz.BookBiz;
import com.book.biz.impl.BookBizImpl;
import com.book.dao.DataResource;

public class SelectBookServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String type = request.getParameter("type");
		
		BookBiz bookBiz = new BookBizImpl();
		if("all".equals(type)){
			List<Book> list = new ArrayList<Book>();
			list = bookBiz.listBook();
			List<Book> recomList = new ArrayList<Book>();
			recomList = bookBiz.recomBook();
			request.setAttribute("recomList", recomList);
			request.setAttribute("list", list);
			request.getRequestDispatcher("main.jsp").forward(request, response);
		}
		if("one".equals(type)){
			int bid = Integer.parseInt(request.getParameter("bid"));
			Book book = bookBiz.getOneBook(bid);
			int hintcount = book.getHintcount()+1;
			bookBiz.modifyBook(bid, hintcount);
			
			request.setAttribute("book", book);
			request.getRequestDispatcher("oneBook.jsp").forward(request, response);
		}
		if("recom".equals(type)){
			List<Book> recomList = new ArrayList<Book>();
			recomList = bookBiz.recomBook();
			request.setAttribute("recomList", recomList);
			request.getRequestDispatcher("main.jsp").forward(request, response);
		}
		//主页全部图书
		if("search".equals(type)){
			String keyword = request.getParameter("keywords");
			
			if(" ".equals(keyword)){
				List<Book> list = new ArrayList<Book>();
				list = bookBiz.listBook();
				request.setAttribute("list", list);
				request.getRequestDispatcher("main.jsp").forward(request, response);
			}else{
				
				List<Book> list = new ArrayList<Book>();
				list = bookBiz.keySearchBook(keyword);
				List<Book> recomList = new ArrayList<Book>();
				recomList = bookBiz.recomBook();
				request.setAttribute("recomList", recomList);
				request.setAttribute("list", list);
				request.getRequestDispatcher("main.jsp").forward(request, response);
			}
		}		
		
	}
	

}
